import React, { Component } from 'react';
import { Tree, Input, message } from 'antd';
import axios from 'axios';
import { connect } from 'react-redux';
import store from '../../../redux/index';

const TreeNode = Tree.TreeNode;
const Search = Input.Search;

const getParentKey = (key, tree) => {
  let parentKey;
  var oKey = key.toString();
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => node.id == oKey)) {
        parentKey = oKey;
      }
    }
  }

  return parentKey;
};


class roleTree extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      dataSource: [],
      intData: [],
      MenuOff: ''
    };
  }


  componentDidMount() {
    this.getMenus();
  }

  componentWillReceiveProps(nextProps) {
    this.state.MenuOff = nextProps.MenuOff;
    // console.log(this.state.MenuOff+"===========================")
    if (this.state.MenuOff == 'SaveOk') {
      this.getMenus();
    } else if (this.state.MenuOff == 'UpDateOk') {
      this.getMenus();
    } else if (this.state.MenuOff == 'deleteOk') {
      this.getMenus();
    }
  }
  // 更新左侧菜单
  getMenus = () => {
    const _this = this;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/admin/group/tree?groupType=1',
      headers: {
        Authorization: Token
      }
    })
      .then(function (response) {
        _this.setState({
          dataSource: response.data,
          MenuOff: ''
        });
      })
      .catch(function (error) {
        console.log(error);
        message.error('服务器开小差啦，请重试！');
      });

  }

  onSelect = (selectedKeys, info) => {
    var _this = this;

    if (info.selectedNodes[0] != undefined) {
      _this.props.getMenuData(info.selectedNodes[0].props.id);
      _this.props.takeID(info.selectedNodes[0].props.id, info.selectedNodes[0].props.parentId);
    }


    store.dispatch({ type: 'changeGroupBtnsStatus', GroupBtnsStatus: true });
    store.dispatch({ type: 'changeGroupBtnsUpate', GroupBtnsUpate: false });
    store.dispatch({ type: 'changeGroupBtnsShow', GroupBtnsShowStatus: true });
  }

  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }
  onChange = (e) => {
    const value = e.target.value;
    const expandedKeys = this.state.dataSource.map((item) => {
      // console.log(item.title.indexOf(value))
      if (item.name.indexOf(value) >= -1) {
        return getParentKey(item.id, this.state.dataSource);
      }
      return null;
    }).filter((item) => item);
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  }

  render() {

    const { searchValue, expandedKeys, autoExpandParent } = this.state;
    const loop = data => data.map((item, key) => {
      const index = item.name.indexOf(searchValue);
      const beforeStr = item.name.substr(0, index);
      const afterStr = item.name.substr(index + searchValue.length);

      const title = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{searchValue}</span>
          {afterStr}
        </span>
      ) : <span>{item.name}</span>;
      if (item.children) {
        return (
          <TreeNode key={item.id} title={title} id={item.id} parentId={item.parentId}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={title} id={item.id} parentId={item.parentId} />;
    });
    return (
      <div>
        <Search style={{ marginBottom: 8 }} placeholder="请输入关键词过滤" onChange={this.onChange} />
        <Tree
          onExpand={this.onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onSelect={this.onSelect}
        >
          {loop(this.state.dataSource)}
        </Tree>
      </div>
    );
  }
}

export default roleTree;